package cn.tedu.micro.demo.dlx;

import cn.tedu.micro.demo.client.RabbitChannelManager;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class DlxDemo {
    /**
     * 参考约定名称和绑定关系 声明一套死信的组件结构
     */
    private static final String BIZ_EX="biz_ex";
    private static final String BIZ_Q="biz_q";
    private static final String DLX_EX="dlx_ex";
    private static final String DLX_Q="dlx_q";
    private static final String DLX_RK="dlx_rk";
    @Test
    public void dlxDelare() throws IOException {
        //1.拿到channel
        Channel channel = RabbitChannelManager.newChannel();
        //2.声明业务交换机
        channel.exchangeDeclare(BIZ_EX, BuiltinExchangeType.FANOUT);
        //3.死信交换机
        channel.exchangeDeclare(DLX_EX,BuiltinExchangeType.DIRECT);
        //4.业务队列
        Map<String,Object> args=new HashMap<>();
        //绑定死信交换机
        args.put("x-dead-letter-exchange",DLX_EX);
        //死信携带路由key
        args.put("x-dead-letter-routing-key",DLX_RK);
        //产生死信原因之一的属性 max-length over-flow(默认drop head)
        args.put("x-max-length",10);
        channel.queueDeclare(BIZ_Q,false,false,false,args);
        //5.死信队列
        channel.queueDeclare(DLX_Q,false,false,false,null);
        //6.业务结构绑定
        channel.queueBind(BIZ_Q,BIZ_EX,"");
        //7.死信结构的绑定
        channel.queueBind(DLX_Q,DLX_EX,DLX_RK);
    }
    @Test
    public void testNackConsme() throws IOException, InterruptedException {
        //1.声明队列
        Channel channel = RabbitChannelManager.newChannel();
        //2.绑定监听消费者
        channel.basicConsume(BIZ_Q,false,
                (consumerTag,message)->{
                    //消费入口
                    log.info("消息达到消费者");
                    //手动确认 requeue: 是否允许重新入队
                    channel.basicNack(
                            message.getEnvelope().getDeliveryTag(),
                            false,
                            false);
                },
                consumerTag->{
                });
        Thread.sleep(10000000);
    }
}
